//
//  FashionDetailView.m
//  花花时尚
//
//  Created by 霍文轩 on 15/8/23.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

#import "FashionDetailView.h"
#import "NetWorkNotify.h"
#import "FashionNewsModel.h"

#import "CollectNewsModel.h"
#import "CollectNewsDatabase.h"

#import "NightMode.h"

#import "GiFHUD.h"

@interface FashionDetailView() <UIScrollViewDelegate,UIWebViewDelegate>{
    int beforeYOffset;
}
@property (nonatomic,retain) FashionNewsModel * model;
@property (nonatomic,retain) UIView * backgroundView; // 背景view，为了透明度动画
@property (nonatomic,retain) UIImageView * thumbImageView;
@property (nonatomic,retain) UIWebView * webView;
@property (nonatomic,retain) UIButton * returnButton; // 返回按钮
@property (nonatomic,assign) CGRect imageRect;
@property (nonatomic,retain) UIView * downView;
@property (nonatomic,copy) NSString * urlString;
@end

@implementation FashionDetailView
- (void)dealloc
{
    [_urlString release];
    [_model release];
    [_downView release];
    
    [_returnButton release];
    [_thumbImageView release];
    [_webView release];
    [super dealloc];
}
-(instancetype)initWithFrame:(CGRect)frame image:(UIImage *)image imageRect:(CGRect)rect model:(FashionNewsModel *)model{
    self = [super initWithFrame:frame];
    if(self){
        self.model = model;
        self.backgroundColor = [UIColor clearColor];
        self.imageRect = rect;
        beforeYOffset = 0;
        
        [self createBackgroundView];
        
        [self createWebViewWithContentId:model.contentid];
        [self createImageViewWithImage:image rect:rect];
        [self createDownView];
    }
    return self;
}
-(void)createBackgroundView{
    // 背景view，为了透明度动画
    self.backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _backgroundView.backgroundColor = [UIColor whiteColor];
    _backgroundView.alpha = 0;
    [self addSubview:_backgroundView];
    [_backgroundView release];
}
-(void)createWebViewWithContentId:(NSInteger)contentId{
    // 创建webview
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _webView.delegate = self;
    _webView.alpha = 0;
    [self setWebWithContentId:contentId];
    
    [self addSubview:_webView];
    
    // 设置webView的scrollView属性
    _webView.scrollView.delegate = self;
    
    [_webView release];
}
-(void)createImageViewWithImage:(UIImage *)image rect:(CGRect)rect{
    // 创建图片
    self.thumbImageView = [[UIImageView alloc] initWithFrame:rect];
    NSInteger cellHeight = _thumbImageView.frame.size.height;
    _thumbImageView.userInteractionEnabled = YES;
    _thumbImageView.alpha = 0;
    self.thumbImageView.image = image;
    [self addSubview:_thumbImageView];
    [_thumbImageView release];
    
    [self createReturnButton];
    
    // 所有的子视图透明度变为1
    [UIView animateWithDuration:0.7 animations:^{
        _thumbImageView.frame = CGRectMake(0, 0, self.frame.size.width, cellHeight);
        _backgroundView.alpha = 1;
        _thumbImageView.alpha = 1;
        _webView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}
-(void)createReturnButton{
    self.returnButton = [[UIButton alloc] initWithFrame:CGRectMake(-50, 10, 50, 50)];
    _returnButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"return"]];
    _returnButton.alpha = 0.6;
    [_returnButton addTarget:self action:@selector(returnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_returnButton];
    
    [UIView animateWithDuration:0.7 animations:^{
        _returnButton.frame = CGRectMake(10, 10, 50, 50);
    }];
    
    [_returnButton release];
}
-(void)createDownView{
    self.downView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height, self.frame.size.width, 49)];

    _downView.backgroundColor = [NightMode nightModeON]?[UIColor lightGrayColor]:[UIColor whiteColor];
    [UIView animateWithDuration:0.7 animations:^{
        _downView.frame = CGRectMake(0, self.frame.size.height-49, self.frame.size.width, 49);
    }];
    [self addSubview:_downView];
    
    
    // 分享
    UIButton * shareButton = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width-50, 10, 27, 30)];
    shareButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"share"]];
    [_downView addSubview:shareButton];
    [shareButton addTarget:self action:@selector(showShareView) forControlEvents:UIControlEventTouchUpInside];
    [shareButton release];
    
    UIButton * collectButton = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width/2-15, 10, 30, 30)];
    if( [CollectNewsDatabase selectWithId:_model.contentid] == nil){
        collectButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"collect"]];
    }else{
        collectButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"collectselected"]];
    }

    [_downView addSubview:collectButton];
    [collectButton addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
    [collectButton release];
    
    [_downView release];
}
-(void)showShareView{
    [self.delegate showShareViewWithTitle:_model.title image:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_model.thumb]]] urlString:_urlString];
}
#pragma mark - 收藏
-(void)collect:(UIButton *)button{
    // 如果在数据库中没查到model，就插入，并改变收藏图标；如果找到了  就删除
    if( [CollectNewsDatabase selectWithId:_model.contentid] == nil){
        CollectNewsModel * collectModel = [CollectNewsModel collectModelWithcontentid:_model.contentid title:_model.title thumb:_model.thumb cat_logo:_model.cat_logo];
        [CollectNewsDatabase insertWithModel:collectModel];
        button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"collectselected"]];
    }else{
        [CollectNewsDatabase deleteWithId:_model.contentid];
        button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"collect"]];
    }
}
// 界面返回
-(void)returnAction:(id)sender{
    [UIView animateWithDuration:0.7 animations:^{
        self.returnButton.frame = CGRectMake(-50, 10, 50, 50);
        _thumbImageView.hidden = NO;
        self.thumbImageView.frame = CGRectMake(_imageRect.origin.x, _imageRect.origin.y-215/2, _imageRect.size.width, _imageRect.size.height); // 215为cell的高度
        for (UIView * subView in [self subviews]) { // 把所有的子视图的alpha设为0
            subView.alpha = 0;
        }
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
    [self.delegate detailWillDisappear];
}
#pragma  mark - URL请求
-(void)setWebWithContentId:(NSInteger)contentId{
    self.urlString = [NSString stringWithFormat:@"http://m.ellechina.com/elleplus/index.php?contentid=%ld&utm_source=weixin&utm_medium=app&utm_campaign=elleplus&s_cid=elleplus&from=singlemessage&isappinstalled=1",(long)contentId];
    NSURLRequest * request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:_urlString]];
    [_webView loadRequest:request];
    NSLog(@"%@",_urlString);
//    [GiFHUD dismiss];
    [request release];
}
#pragma mark - UIScrollView代理
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int currentYOffset = scrollView.contentOffset.y;
    // 向上拉
    if(currentYOffset > beforeYOffset){ // 判断上拉还是下降
        // 如果不在顶部并且上拉，就让downView藏起来
        if(scrollView.contentOffset.y>0){
            [UIView animateWithDuration:0.7 animations:^{
                _downView.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, 49);
            }];
        }
        // 如果图片没有回到原来位置就还原大小，如果在原来位置就上升
        if(scrollView.contentOffset.y>0)
            _thumbImageView.frame = CGRectMake(0, -scrollView.contentOffset.y, _thumbImageView.frame.size.width, _thumbImageView.frame.size.height);
        else{
            _thumbImageView.frame = CGRectMake(0, 0, _imageRect.size.width-scrollView.contentOffset.y, _imageRect.size.height-scrollView.contentOffset.y);
            _thumbImageView.center = CGPointMake(self.frame.size.width/2,( _imageRect.size.width - scrollView.contentOffset.y)/2);  // 因为直接加到cell上，而不是cell的contentView上，坐标是反得，所以需要用width - ；一般用height + 
        }
    }
    else{  // 向下拉时图片随着变大
        if( (beforeYOffset - currentYOffset ) > 15) // 向上拉时候拉动过快才显示downView
            [UIView animateWithDuration:0.7 animations:^{
                _downView.frame = CGRectMake(0, self.frame.size.height-49, self.frame.size.width, 49);
            }];
        if(scrollView.contentOffset.y<0)
        {
            _thumbImageView.frame = CGRectMake(0, 0, _imageRect.size.width-scrollView.contentOffset.y, _imageRect.size.height-scrollView.contentOffset.y);
            _thumbImageView.center = CGPointMake(self.frame.size.width/2,( _imageRect.size.width - scrollView.contentOffset.y)/2);
        }else{
            _thumbImageView.frame = CGRectMake(0, -scrollView.contentOffset.y, _thumbImageView.frame.size.width, _thumbImageView.frame.size.height);
        }
    }
    beforeYOffset = currentYOffset;
}
#pragma mark - webView代理
// 开始加载时显示加载中
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    self.mb = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
//    _mb.userInteractionEnabled = NO; // 让它不可点击
//    [self addSubview:_mb];
//    
//    _mb.labelText = @"加载中...";
//    [_mb show:YES];
    [GiFHUD show];
    return YES;
}
// 加载完成时候，如果网页的数据正常，那么显示；如果不正常，创建一个button刷新网页
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    [GiFHUD dismiss];
    
    NSString * documentTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];// 得到网页的标题
    NSString * subString = [documentTitle substringWithRange:NSMakeRange(0, 2)];
    if([subString isEqualToString:@"50"]){
        [self failLoad];
    }else {
        if( ! [_model.video isEqualToString:@""]){ // 如果视频地址不为空，那么隐藏图片，让视频可以点击观看
            _thumbImageView.hidden = YES;
        }
        // 网页加载完成并且没有错误才显示webView
//        [GiFHUD dismiss];
        [self addSubview:_webView];
        // 需要把return按钮和图片放在上面
        [self addSubview:_thumbImageView];
        [self addSubview:_returnButton];
        [self addSubview:_downView];
        [UIView animateWithDuration:0.7 animations:^{ // 下面的视图出现
            _downView.frame = CGRectMake(0, self.frame.size.height-49, self.frame.size.width, 49);
        }];
    }
}
// 网页加载失败
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [GiFHUD dismiss];
    [self failLoad];
}
#pragma mark - 加载失败执行的方法，创建一个重新加载的按钮
-(void)failLoad{
    [_webView removeFromSuperview]; // 如果网页出错，将webView删除
    
    UIButton * reloadWebButton  =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 50)];
    reloadWebButton.center = CGPointMake(self.frame.size.width/2,_thumbImageView.frame.size.height+((self.frame.size.height-_thumbImageView.frame.size.height))/2 );
    reloadWebButton.titleLabel.font = [UIFont boldSystemFontOfSize:25];
    [reloadWebButton setTitle:@"加载失败，点击重新加载" forState:UIControlStateNormal];
    [reloadWebButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [reloadWebButton addTarget:self action:@selector(reloadWebAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:reloadWebButton];
    [reloadWebButton release];
}
// 重新刷新webView
-(void)reloadWebAction:(UIButton *)reloadWebButton{
    [_webView reload];
    [reloadWebButton removeFromSuperview];
}
@end
